﻿<%@ WebHandler Language="C#" Class="user" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;

using VISS.API.Users;
using NCT.Framework;
using VISS.Web.BackEnd;
using VISS.MailImpl;
using NCT.Mail;


public class user : IHttpHandler, IRequiresSessionState {

    class UserMailEnt {
        public string Name { get; set; }
        public string Email { get; set; }
        
        public UserMailEnt(string name, string email) {
            Name = name;
            Email = email;
        }
    }
    private delegate void DelSendMail(string title, string content, List<UserMailEnt> userList);
    private void SendMail(string title, string content, List<UserMailEnt> userList) {

        for (int i = 0; i < userList.Count; i++) {
            MailEnt.MailNotification ent = new MailEnt.MailNotification();
            ent.Subject = "VISS - Thông báo từ VISS";
            ent.Title = title;
            ent.Content = content;
            ent.Email = userList[i].Email;
            ent.FullName = userList[i].Name;
            ent.UserKey = "NoNeed";
            MailEnt.MailInfo mailInfo = new MailEnt.MailInfo();
            mailInfo.MailContent = SerializerUtils.JsonSerialize(ent);
            mailInfo.SendMailType = ESendMailType.Notification;

            try {
                if (NCT.Mail.MailQueuePD.CreateInstance().AddToQueue(AppSettings.MailType, SerializerUtils.JsonSerialize(mailInfo)) <= 0) {
                    LogUtils.Error("Sent mail:frontend.viss.vn: send mail to user fail.");
                }
            }
            catch (Exception ex) {
                LogUtils.Error("Sent mail fail: " + ex.ToString());
            }
        }
    }
    
    private const string _resultTemplate = "{{\"result\":\"{0}\"}}";
    
    public void ProcessRequest (HttpContext context) {
        string action = context.Request.Form["action"];
        switch(action) {
            case "edituser":
                UpdateUser(context);
                break;
            case "editgeneral":
                UpdateGeneral(context);
                break;
            case "editappearance":
                UpdateAppearance(context);
                break;
            case "editliving":
                UpdateLiving(context);
                break;
            case "editfamily":
                UpdateFamily(context);
                break;
            case "editculture":
                UpdateCulture(context);
                break;
            case "editcontactinfo":
                UpdateContactInfo(context);
                break;
            case "activeUser":
                ActiveUser(context);
                break;
            case "verifyUser":
                VerifyUser(context);
                break;
            case "unVerifyUser":
                UnVerifyUser(context);
                break;
            case "disableUser":
                DisableUser(context);
                break;
            case "unDisableUser":
                UnDisableUser(context);
                break;
            case "resetPassword":
                ResetPassword(context);
                break;
            case "deleteReport":
                DeleteReport(context);
                break;
            case "sendMail":
                SendMail(context);
                break;
            case "sendMailUpload":
                SendMailUpload(context);
                break;
        }
    }
    
    private void UpdateUser(HttpContext context) {
        int result = 1;
        try {
            UserAdminEnt item = new UserAdminEnt();    
            item.UserKey = context.Request.Form["userkey"];
            item.Status = (EUserStatus)ConvertUtils.ToShort(context.Request.Form["status"]);
            
            if(!StructureMapFactory.GetInstance<IUserAdmin>().UpdateStatus(item)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result.ToString()));
        }        
    }

    private void UpdateGeneral(HttpContext context) {
        int result = 1;
        try {
            UserGeneralProfileEnt item = new UserGeneralProfileEnt();
            item.UserKey = context.Request.Form["userkey"];
            item.Name = context.Request.Form["name"];
            item.Gender = (EUserGender)ConvertUtils.ToByte(context.Request.Form["gender"]);
            item.BirthDate = ConvertUtils.ToDateTime(context.Request.Form["birthdate"], "dd/mm/yyyy");
            item.CityID = ConvertUtils.ToShort(context.Request.Form["city"]);
            item.EducationID = ConvertUtils.ToShort(context.Request.Form["education"]);
            item.JobID = ConvertUtils.ToShort(context.Request.Form["job"]);
            item.Hobby = context.Request.Form["hobby"];
            item.Blast = context.Request.Form["blast"];
            item.LookingFor = (EUserLookingFor)ConvertUtils.ToByte(context.Request.Form["lookingfor"]);

            if (!StructureMapFactory.GetInstance<IUserGeneralProfileAdmin>().Update(item)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result.ToString()));
        }
    }

    private void UpdateCulture(HttpContext context) {
        int result = 1;
        try {
            UserCultureProfileEnt item = new UserCultureProfileEnt();
            item.UserKey = context.Request.Form["userkey"];
            item.ReligionID = ConvertUtils.ToShort(context.Request.Form["religion"]);

            if (!StructureMapFactory.GetInstance<IUserCultureProfileAdmin>().Update(item)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result.ToString()));
        }        
    }

    private void UpdateFamily(HttpContext context) {
        int result = 1;
        try {
            UserFamilyProfileEnt item = new UserFamilyProfileEnt();
            item.UserKey = context.Request.Form["userkey"];
            item.MaritalStatusID = ConvertUtils.ToShort(context.Request.Form["maritalstatus"]);

            if (!StructureMapFactory.GetInstance<IUserFamilyProfileAdmin>().Update(item)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result.ToString()));
        }    
    }

    private void UpdateLiving(HttpContext context) {
        int result = 1;
        try {
            UserLivingProfileEnt item = new UserLivingProfileEnt();
            item.UserKey = context.Request.Form["userkey"];
            item.SmokingID = ConvertUtils.ToShort(context.Request.Form["smoking"]);
            item.Income = ConvertUtils.ToInt(context.Request.Form["income"]);

            if (!StructureMapFactory.GetInstance<IUserLivingProfileAdmin>().Update(item)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result.ToString()));
        }    
    }

    private void UpdateContactInfo(HttpContext context) {
        int result = 1;
        try {
            UserContactInfoEnt item = new UserContactInfoEnt();
            item.UserKey = context.Request.Form["userkey"];

            if (!StructureMapFactory.GetInstance<IUserContactInfoAdmin>().Update(item)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result.ToString()));
        }    
    }

    private void UpdateAppearance(HttpContext context) {
        int result = 1;
        try {
            UserApperanceProfileEnt item = new UserApperanceProfileEnt();
            item.UserKey = context.Request.Form["userkey"];
            item.Height = ConvertUtils.ToShort(context.Request.Form["height"]);
            item.Weight = ConvertUtils.ToShort(context.Request.Form["weight"]);
            
            if(!StructureMapFactory.GetInstance<IUserAppearanceProfileAdmin>().Update(item)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result.ToString()));
        }    
    }

    private void ActiveUser(HttpContext context) {
        int result = 1;
        string userKey = string.Empty;
        try {
            userKey = context.Request.Form["userkey"];

            if (!StructureMapFactory.GetInstance<IUserAdmin>().UpdateStatus(userKey, EUserStatus.Actived)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result));
        }
    }

    private void VerifyUser(HttpContext context) {
        int result = 1;
        string userKey = string.Empty;
        try {
            userKey = context.Request.Form["userkey"];

            if (!StructureMapFactory.GetInstance<IUserAdmin>().VefifyUser(userKey)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result));
        }    
    }

    private void UnVerifyUser(HttpContext context) {
        int result = 1;
        string userKey = string.Empty;
        try {
            userKey = context.Request.Form["userkey"];

            if (!StructureMapFactory.GetInstance<IUserAdmin>().UnVefifyUser(userKey)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result));
        }
    }

    private void DisableUser(HttpContext context) {
        int result = 1;
        string userKey = string.Empty;
        try {
            userKey = context.Request.Form["userkey"];

            if (!StructureMapFactory.GetInstance<IUserAdmin>().DisableUser(userKey)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result));
        }
    }

    private void UnDisableUser(HttpContext context) {
        int result = 1;
        string userKey = string.Empty;
        try {
            userKey = context.Request.Form["userkey"];

            if (!StructureMapFactory.GetInstance<IUserAdmin>().UnDisableUser(userKey)) {
                result = 0;
            }
        }
        catch {
            result = 0;
        }
        finally {
            FormValidateUtils.Return(string.Format(_resultTemplate, result));
        }
    }

    private void ResetPassword(HttpContext context) {
        string resultTemplate = "{{\"result\":\"{0}\",\"newPass\":\"{1}\"}}";
        string userKey = string.Empty;
        string password = string.Empty;
        userKey = context.Request.Form["userkey"];

        if (!StructureMapFactory.GetInstance<IUserAdmin>().ResetPassword(userKey, out password)) {
            FormValidateUtils.Return(string.Format(resultTemplate, 0));
        }

        FormValidateUtils.Return(string.Format(resultTemplate, 1, password));
    }

    private void DeleteReport(HttpContext context) {
        long reportID = ConvertUtils.ToLong(context.Request.Form["reportID"]);
        string reportedUserKey = ConvertUtils.ToString(context.Request.Form["reportedUserKey"]);
        
        if (!StructureMapFactory.GetInstance<IUserReportAdmin>().Delete(reportID)) {
            FormValidateUtils.Return(string.Format(_resultTemplate, 0));
            return;
        }
        FormValidateUtils.Return(string.Format(_resultTemplate, 1));
    }
    
    private void SendMail(HttpContext context) {
        string resultTemplate = "{{\"result\":\"{0}\",\"failed\":\"{1}\"}}";
        
        string title = ConvertUtils.ToString(context.Request.Form["title"]);
        string content = ConvertUtils.ToString(context.Request.Form["content"]);
        content = content.Replace("\"", "'");
        string users = ConvertUtils.ToString(context.Request.Form["users"]);

        string[] userList = users.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
        List<UserMailEnt> validUserList = new List<UserMailEnt>();
        string failed = string.Empty;
        for (int i = 0; i < userList.Length; i++) {
            string[] user = userList[i].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            if (!Commons.IsEmail(user[1])) {
                failed += "," + user[0];
                continue;
            }
            UserMailEnt item = new UserMailEnt(user[0], user[1]);
            validUserList.Add(item);
        }
        DelSendMail del = new DelSendMail(SendMail);
        del.Invoke(title, content, validUserList);

        if (failed.Length > 0) {
            failed = failed.Substring(1);
            FormValidateUtils.Return(string.Format(resultTemplate, 2, failed));
            return;
        }
        FormValidateUtils.Return(string.Format(resultTemplate, 1, ""));
    }

    private void SendMailUpload(HttpContext context) {
        string resultTemplate = "{{\"result\":\"{0}\",\"failed\":\"{1}\"}}";

        string title = ConvertUtils.ToString(context.Request.Form["txtTitle"]);
        string content = ConvertUtils.ToString(context.Request.Form["txtContent"]);
        content = content.Replace("|lt", "<").Replace("|gt", ">").Replace("\"", "'");

        string ext = string.Empty;
        string fileName = context.Request.Files["FileEmail"].FileName;

        int index = fileName.LastIndexOf(".");
        if (index > 0) {
            ext = fileName.Substring(index);            
        }
        if (string.Compare(ext, ".txt", true) != 0) {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write("<script type='text/javascript'>");
            HttpContext.Current.Response.Write("window.parent.SendMailSuccess('2', '0');window.close();");
            HttpContext.Current.Response.Write("</script>");
            return;
        }
        string folderPath = context.Server.MapPath(@"/res/") + "tmp";
        if (!FileUtils.CreateFolderForFile(folderPath)) {
            FormValidateUtils.Return(string.Format(resultTemplate, 0, ""));
            return;
        }
        System.IO.Stream st = context.Request.Files[0].InputStream;
        using (System.IO.FileStream fileStream = System.IO.File.Create(folderPath + "/userlist.txt", (int)st.Length)) {
            // Fill the bytes[] array with the stream data
            byte[] bytesInStream = new byte[st.Length];
            st.Read(bytesInStream, 0, (int)bytesInStream.Length);

            // Use FileStream object to write to the specified file
            fileStream.Write(bytesInStream, 0, bytesInStream.Length);
            fileStream.Close();
        }
        System.IO.StreamReader reader = new System.IO.StreamReader(folderPath + "/userlist.txt");
        string line;
        int failed = 0;
        List<UserMailEnt> validUserList = new List<UserMailEnt>();
        while ((line = reader.ReadLine()) != null) {
            string[] user = line.Split('\t');
            if (!Commons.IsEmail(user[1])) {
                failed++;
                continue;
            }
            UserMailEnt item = new UserMailEnt(user[0], user[1]);
            validUserList.Add(item);
        }
        reader.Close();
        
        DelSendMail del = new DelSendMail(SendMail);
        del.Invoke(title, content, validUserList);
        
        if (failed > 0) {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write("<script type='text/javascript'>");
            HttpContext.Current.Response.Write("window.parent.SendMailSuccess('3', '" + failed + "');window.close();");
            HttpContext.Current.Response.Write("</script>");
            return;
        }
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write("<script type='text/javascript'>");
        HttpContext.Current.Response.Write("window.parent.SendMailSuccess('1', '0');window.close();");
        HttpContext.Current.Response.Write("</script>");
    }    
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}